using System.Collections.Generic;
using DG.Tweening;
using Dream.Dialogue.Implement;
using Light;
using Light.Assets.Scripts.EventManager;
using UnityEngine;
using UnityEngine.UI;

namespace Dream.SecondLevel
{
    //sky 24-11-24 14:43 

    public enum ChangeSprite
    {
        Character,
        Background
    }

    public class GalTextController : MonoBehaviour
    {
        public AudioClip bgm;

        public Text speakerName;
        public Image backgroundImage;
        public Image aliceSprite;
        public Image aikoSprite;
        [SerializeField] private Button firstOption;
        [SerializeField] private Button SecondOption;

        private readonly string _fileName = Constants.CURRENT_STORY_FILENAME;
        private bool _continueTalk;
        private int _currentLine = Constants.DEFAULT_START_LINE;
        private bool _isContinue = true;

        private List<ExcelReader.ExcelData> _storyData;
        private InteractTalk _talkBase;

        //选择分支
        private GameObject choice;
        private Text fOptionText;
        private bool isNow;
        private Text sOptionText;

        private void Start()
        {
            Init();
            ButtonBindFunctions();
            ExcelReader.LoadExcelData(_fileName, OnExcelDataLoaded);
            AudioManager.Instance.setBGM(bgm);
        }

        // Update is called once per frame
        private void Update()
        {
            _continueTalk = LightInputManager.Instance.ContinueTalkInput;
            if (_continueTalk && _isContinue)
            {
                if (_currentLine == _storyData.Count - 1)
                {
                    if (_storyData[_currentLine].choiceOfEnd == Constants.END_OF_STORY)
                    {
                        ExitDream();
                        return;
                    }

                    if (_storyData[_currentLine].choiceOfEnd == Constants.CHOICE)
                    {
                        DisplayNextLine();
                        return;
                    }
                }

                DisplayNextLine();
                ChangeOperation();
            }
        }

        private void OnDestroy()
        {
            firstOption.onClick.RemoveAllListeners();
            SecondOption.onClick.RemoveAllListeners();
        }

        private void OnExcelDataLoaded(List<ExcelReader.ExcelData> excelDataList)
        {
            if (excelDataList != null)
            {
                _storyData = excelDataList;
                DisplayNextLine();
                ChangeOperation();
            }
            else
            {
                Debug.Log("失败");
            }
        }

        private void Init()
        {
            _talkBase = GetComponentInChildren<InteractTalk>();
            speakerName = GetComponentsInChildren<Text>()[1];
            choice = transform.Find("Choice").gameObject;
            firstOption = choice.GetComponentsInChildren<Button>()[0];
            SecondOption = choice.GetComponentsInChildren<Button>()[1];
            fOptionText = firstOption.GetComponentInChildren<Text>();
            sOptionText = SecondOption.GetComponentInChildren<Text>();
            choice.SetActive(false);
        }

        private void ButtonBindFunctions()
        {
            firstOption.onClick.AddListener(FirstOptionClick);
            SecondOption.onClick.AddListener(SecondOptionClick);
        }

        private void ExitDream()
        {
            using var evt = NextSceneLoad.Get();
            evt.isFadeScreen = true;
            evt.isExitScene = true;
            EventManager.SendEvent(evt);
            AudioManager.Instance.PauseBGM();
        }

        //角色行为，背景，角色立绘的更改
        private void ChangeOperation()
        {
            //背景
            if (!isNow && _currentLine > 0 && NotNullNorEmpty(_storyData[_currentLine - 1].backGroundImageFileName))
                UpdataSprite(Constants.BACKGROUND_PATH, _storyData[_currentLine - 1].backGroundImageFileName,
                    backgroundImage);
            //立绘
            if (!isNow && _currentLine > 0 && NotNullNorEmpty(_storyData[_currentLine - 1].characterSpriteFileName))
            {
                if (_storyData[_currentLine - 1].speaker == Constants.CHARACTER_NAME1)
                    UpdataSprite(Constants.CHARACTER_PATH, _storyData[_currentLine - 1].characterSpriteFileName,
                        aliceSprite);
                else if (_storyData[_currentLine - 1].speaker == Constants.CHARACTER_NAME2)
                    UpdataSprite(Constants.CHARACTER_PATH, _storyData[_currentLine - 1].characterSpriteFileName,
                        aikoSprite);
            }

            //动作
            if (!isNow && _currentLine > 0 && NotNullNorEmpty(_storyData[_currentLine - 1].characterAction))
                StartAction(_storyData[_currentLine - 1].characterAction);
        }

        //播放对话
        private void DisplayNextLine()
        {
            var data = _storyData[_currentLine];
            _talkBase.SetWord(data.content);
            isNow = _talkBase.StartTalk();
            if (!isNow)
            {
                speakerName.text = data.speaker == Constants.ISNARRATOR ? "" : data.speaker;
                ++_currentLine;
            }

            ShowChoice();
        }

        private bool NotNullNorEmpty(string str)
        {
            return !string.IsNullOrEmpty(str);
        }

        //更改背景和角色
        private void UpdataSprite(string Path, string filePath, Image changeSprite)
        {
            var imagePath = Path + filePath;
            var sprite = Resources.Load<Sprite>(imagePath);
            if (sprite != null) changeSprite.sprite = sprite;
        }

        //执行角色行为
        private void StartAction(string action)
        {
            Image currentImage;
            //确定执行人
            if (_storyData[_currentLine - 1].executor == Constants.CHARACTERISALICE)
                currentImage = aliceSprite;
            else
                currentImage = aikoSprite;
            //消失
            if (action == Constants.CHARACTERACTIONDISAPPEAR)
                currentImage.DOFade(0, Constants.DOACTION_TIME)
                    .OnComplete(() => currentImage.gameObject.SetActive(false));
            //出现
            if (action.StartsWith(Constants.CHARACTERACTIONAPPEARAT))
                AppearAction(action, currentImage);
            //移动
            if (action.StartsWith(Constants.CHARACTERACTIONMOVETO))
                MoveAction(action, currentImage);
        }

        //出现行为
        private void AppearAction(string action, Image currentImage)
        {
            //出现位置
            var coordinate = action[9..^1].Split('.');
            var x = float.Parse(coordinate[0]);
            currentImage.rectTransform.anchoredPosition =
                new Vector2(x, currentImage.rectTransform.anchoredPosition.y);
            currentImage.gameObject.SetActive(true);
            //淡入效果
            currentImage.DOFade(1, Constants.DOACTION_TIME).From(0);
        }

        // 移动行为
        private void MoveAction(string action, Image currentImage)
        {
            var coordinate = action[7..^1].Split(',');
            var x = float.Parse(coordinate[0]);
            //移动动画
            currentImage.rectTransform.DOAnchorPosX(x, Constants.DOACTION_TIME);
        }

        //选择的处理
        private void ShowChoice()
        {
            //选项的设置和之后对话的处理
            if (isNow || _currentLine < _storyData.Count) return;
            fOptionText.text = _storyData[_currentLine - 1].backGroundImageFileName;
            sOptionText.text = _storyData[_currentLine - 1].characterSpriteFileName;
            choice.SetActive(true);
            _isContinue = false;
        }

        //选项按钮的绑定函数
        private void FirstOptionClick()
        {
            ExcelReader.LoadExcelData(_storyData[_currentLine - 1].firstChoiceFile, OnExcelDataLoaded);
            _currentLine = Constants.DEFAULT_START_LINE;
            _isContinue = true;
            choice.SetActive(false);
            DisplayNextLine();
        }

        private void SecondOptionClick()
        {
            ExcelReader.LoadExcelData(_storyData[_currentLine - 1].secondChoiceFile, OnExcelDataLoaded);
            _currentLine = Constants.DEFAULT_START_LINE;
            _isContinue = true;
            choice.SetActive(false);
            DisplayNextLine();
        }
    }
}